public class DataStack {//ջ
    private int index=0;//±
    private char data[]=new char[10];//ݴ洢
    public synchronized void push(char c) {//
    	while(index==data.length){//ͬ
    	    try{
    	    	this.wait();//ȴ
    	    	}catch(InterruptedException e){}
    	}
    	this.notify();//߳
    	data[index]=c;//
    	index++;//޸±
    	System.out.println("Input data: "+c);//
    }
    public synchronized char pop(){//ȡ
        while(index==0){//ͬ
        	try{
    	    	this.wait();//ȴ
    	    	}catch(InterruptedException e){}
        	}
        this.notify();//߳
        index--;//޸±
        System.out.println("Output data: "+data[index]);//
        return data[index];//
    }
}
public class WriterPerson extends Thread{//дݵ߳
    DataStack stack;
    public WriterPerson(DataStack stack) {
    	this.stack=stack;
    }
    public void run(){
    	char c;
    	for(int i=0;i<5;i++){
    		c=(char)(Math.random()*26+'a');
    		stack.push(c);//д
    		try{
    	        this.sleep((int)(Math.random()*500));//ͣ߳0.5
    	    }catch(InterruptedException e){
    	    	e.printStackTrace();
    	    }
    	}
    }
}

public class ReaderPerson extends Thread{//ȡݵ߳
    DataStack stack;
    public ReaderPerson(DataStack stack) {
    	this.stack=stack;
    }
    public void run(){
    	for(int i=0;i<5;i++){
    		stack.pop();//ȡ
    		try{
    	        this.sleep((int)(Math.random()*1000));//ͣ߳0.5
    	    }catch(InterruptedException e){
    	    	e.printStackTrace();
    	    }
    	  }
    }
}

public class StackTest {//
      public static void main(String[] args) {
    	  DataStack stack=new DataStack();//ջ
        WriterPerson wp=new WriterPerson(stack);//д߳
        ReaderPerson rp=new ReaderPerson(stack);//߳
        wp.start();//߳
        rp.start();
    }
}
